package com.qly.jsoup.service.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Andy ye on 2018/8/27.
 */
public class HttpUtils {

    public static String getHtmlContent(String url, String encoding) {
        URL uri = null;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bReader = null;
        StringBuffer sBuffer = new StringBuffer();

        try {
            // 建立网络连接
            uri = new URL(url);
            // 打开连接
            urlConnection = uri.openConnection();
            //输入流
            inputStream = urlConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, encoding);
            bReader = new BufferedReader(inputStreamReader);
            String temp;
            while ((temp = bReader.readLine()) != null) {
                sBuffer.append(temp + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //关闭资源
            if (bReader != null) {
                try {
                    bReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sBuffer.toString();
    }


    public static String httpGet(String url,String encoding) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = null;

        try {

            httpClient = HttpClients.createDefault(); // 创建httpClient实例

            HttpGet httpGet = new HttpGet(url); // 创建httpget实例
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36"); // 设置请求头消息User-Agent

            response = httpClient.execute(httpGet); // 执行http get请求
            HttpEntity entity = response.getEntity(); // 获取返回实体
            result = EntityUtils.toString(entity, encoding);
            System.out.println("网页内容：" + result); // 获取网页内容

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close(); // response关闭
                httpClient.close(); // httpClient关闭
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result;
    }


}
